<?php

namespace app\api\controller;

use app\admin\service\GoodsQrcode;
use app\common\model\GoodsLogModel;
use app\common\model\GoodsProductModel;
use app\common\model\OrderConfigModel;
use app\common\model\OrderGoodsModel;
use app\common\model\OrderLogModel;
use app\common\model\OrderMchModel;
use app\common\model\OrderPaylogModel;
use app\common\model\OrderModel;
use app\common\model\GoodsModel;
use app\common\model\PosthouseModel;
use app\common\model\UserModel;
use think\Db;

/**
 * 定时任务
 */
class Task
{
    /**
     * 商户平台打款给驿站长和合伙人，每日每笔不能超过5000元
     * 超过5000的将会把金额分多天，假如是12000，则分5000，5000，2000分三天
     */
    public function runPaylog()
    {
        $config = config('wechat.miniapp');
        $payment = new \WeChat\Pay($config);
        $log = OrderPaylogModel::where('not_pay', 'neq' ,0)->select()->toArray();
        foreach ($log as $key=>$value){
            if($value['type']==1){
                $type_name = '驿站长';
            }else{
                $type_name = '合伙人';
            }
            if($value['update_time']==null || strtotime($value['update_time'])+86400 < time()) {
                if($value['not_pay']<=5000){//未付不超过5000
                    $options = [
                        'partner_trade_no' => time().uniqid('huilife'),
                        'openid'           => $value['openid'],
                        'check_name'       => 'NO_CHECK',
                        'amount'           => $value['not_pay'] * 100,
                        'desc'             => '转账给'.$type_name,
                        'spbill_create_ip' => '127.0.0.1',
                    ];
                    $result = $payment->createTransfers($options);
                    if($result['result_code']=="SUCCESS"){
                        //写入驿站长与合伙人分润-商户平台转账记录
                        OrderMchModel::where('')->insert([
                            'openid'=>$value['openid'],
                            'poster_id_id'=>$value['poster_id'],
                            'partner_id'=>$value['partner_id'],
                            'type'=>$value['type'],
                            'order_id'=>$value['order_id'],
                            'return_code'=>$result['return_code'],
                            'return_msg'=>$result['return_msg'],
                            'mch_appid'=>$result['mch_appid'],
                            'mch_id'=>$result['mchid'],
                            'nonce_str'=>$result['nonce_str'],
                            'result_code'=>$result['result_code'],
                            'partner_trade_no'=>$result['partner_trade_no'],
                            'payment_no'=>$result['payment_no'],
                            'payment_time'=>$result['payment_time'],
                        ]);
                        //写入驿站长与合伙人分润表
                        OrderPaylogModel::where('id',$value['id'])->update([
                            'has_pay'=>$value['has_pay']+$value['not_pay'],
                            'not_pay'=>0,
                            'update_time'=>date('Y-m-d H:i:s',time())
                        ]);
                        echo '订单'.$value['order_id'].'转账'.$value['not_pay'].'元成功、';
                    }
                    else{
                        echo '订单'.$value['order_id'].'转账失败、';
                    }
                }
                else {
                    //如果超过5000，则先结算5000，剩下的纳入未结算表用于定时任务，每天补钱
                    $options = [
                        'partner_trade_no' => time() . uniqid('hdd'),
                        'openid' => $value['openid'],
                        'check_name' => 'NO_CHECK',
                        'amount' => 5000 * 100,
                        'desc' => '转账给'.$type_name,
                        'spbill_create_ip' => '127.0.0.1',
                    ];
                    $result = $payment->createTransfers($options);

                    if ($result['result_code'] == "SUCCESS") {
                        //写入驿站长与合伙人分润-商户平台转账记录
                        OrderMchModel::where('')->insert([
                            'openid'=>$value['openid'],
                            'poster_id_id'=>$value['poster_id'],
                            'partner_id'=>$value['partner_id'],
                            'type'=>$value['type'],
                            'order_id'=>$value['order_id'],
                            'return_code'=>$result['return_code'],
                            'return_msg'=>$result['return_msg'],
                            'mch_appid'=>$result['mch_appid'],
                            'mch_id'=>$result['mchid'],
                            'nonce_str'=>$result['nonce_str'],
                            'result_code'=>$result['result_code'],
                            'partner_trade_no'=>$result['partner_trade_no'],
                            'payment_no'=>$result['payment_no'],
                            'payment_time'=>$result['payment_time'],
                        ]);
                        //写入驿站长与合伙人分润表
                        OrderPaylogModel::where('id', $value['id'])->update([
                            'has_pay' => $value['has_pay'] + 5000,
                            'not_pay' => $value['not_pay'] - 5000,
                            'update_time' => date('Y-m-d H:i:s', time())
                        ]);
                        echo '订单'.$value['order_id'].'转账5000元成功、';
                    }
                    else{
                        echo '订单'.$value['order_id'].'转账失败、';
                    }
                }
            }
        }
    }

    /**
     * 超过时间自动自提完成
     */
    public function autoTake(){
        $order = OrderModel::where('status',ORDER_STATUS_ZITI)->select();
        $send_time = OrderConfigModel::where('key','send_time')->value('value');
        foreach($order as $vo){
            if(strtotime($vo['pay_time']) + intval($send_time) * 86400 < time()){
                $order_id = $vo['id'];
                OrderModel::where(['id'=>$order_id])->update(['status'=>ORDER_STATUS_FINISH]);
                /**
                 * 计算提成给驿站长/合伙人
                 * 调用微信商户平台转账给个人接口
                 */
                //找到订单金额和用户openid
                $order_info =  OrderModel::where(['id'=>$order_id])->field('post_id,order_amount,user_id')->find();

                //找到商品（只有一种）
                $order_goods_info =  OrderGoodsModel::where(['order_id'=>$order_id])->field('goods_id')->find();

                //找到对应的驿站长和合伙人分成比例
                $goods_info =  GoodsModel::where(['id'=> $order_goods_info['goods_id']])->field('poster_rate,partner_rate')->find();
                $poster_rate = $goods_info['poster_rate'];
                $partner_rate = $goods_info['partner_rate'];

                //找到订单对应的驿站的驿站长和合伙人
                $posthouse = PosthouseModel::where('id',$order_info['post_id'])->field('poster_userid,partner_userid')->find();
                $poster_userid = $posthouse['poster_userid'];
                $poster_user = UserModel::where('id',$poster_userid)->find();
                $partner_userid = $posthouse['partner_userid'];
                $partner_user = UserModel::where('id',$partner_userid)->find();

                $order_amount = $order_info['order_amount'];
                $poster_order_amount = $order_amount * $poster_rate/100;
                $partner_order_amount = $order_amount * $partner_rate/100;

                //写入驿站长与合伙人分润表
                //驿站长
                OrderPaylogModel::where('')->insert([
                    'openid'=>$poster_user['openid'],
                    'user_id'=>$poster_userid,
                    'order_id'=>$order_id,
                    'need_pay'=>$poster_order_amount,
                    'has_pay'=>0,
                    'not_pay'=>$poster_order_amount,
                    'create_time'=>date('Y-m-d H:i:s',time()),
                    'type'=>1
                ]);
                //合伙人
                OrderPaylogModel::where('')->insert([
                    'openid'=>$partner_user['openid'],
                    'user_id'=>$partner_userid,
                    'order_id'=>$order_id,
                    'need_pay'=>$partner_order_amount,
                    'has_pay'=>0,
                    'not_pay'=>$partner_order_amount,
                    'create_time'=>date('Y-m-d H:i:s',time()),
                    'type'=>2
                ]);
                //写入商品日志表
                GoodsLogModel::where('')->insert([
                    'user_id'=>$order_info['user_id'],
                    'content'=> '你的商品'.$goods_info['name'].'已经成功自提',
                    'remark'=> '',
                    'create_time'=>date('Y-m-d H:i:s',time())
                ]);
                //订单日志-用户
                $nickname = UserModel::where('id',$order_info['user_id'])->value('nickname');
                OrderLogModel::where('')->insert([
                    'order_id'=>$order_id,
                    'operate_id'=>$order_info['user_id'],
                    'operate_name'=>$nickname,
                    'content'=> '平台自动确认自提',
                    'type'=> 2,
                    'create_time'=>date('Y-m-d H:i:s',time())
                ]);
                echo '订单'.$vo['order_no'].'自动确认自提成功。\r\n';
            }
        }
    }

    /**
     * 超时自动取消订单
     */
    public function autoCancelOrder(){
        $order = OrderModel::where('status',ORDER_STATUS_PAY)->select();
        foreach ($order as $key=>$value){
            $create_time = $value['create_time'];
            $remain_time = OrderConfigModel::where('key','pay_time')->value('value');
            $remain_time = strtotime($create_time) - time() + $remain_time * 60 ;
            if($remain_time<=0){
                OrderModel::where('id',$value['id'])->update([
                    'status'=>ORDER_STATUS_CANCEL
                ]);
                //库存恢复
                $order_goods = OrderGoodsModel::where('order_id',$value['id'])->find();
                $goods = GoodsModel::where('id',$order_goods['goods_id'])->find();
                if($goods['type']==SINGLE_GOODS){
                    GoodsModel::where('id',$order_goods['goods_id'])->setInc('stock',$order_goods['goods_num']);
                }else{
                    GoodsProductModel::where('id',$order_goods['goods_id'])
                        ->where('spec',$order_goods['goods_price'])
                        ->setInc('stock',$order_goods['goods_num']);
                }
                echo '订单'.$value['order_no'].'自动取消成功。\r\n';
            }
        }
    }

    /**
     * 商品分享二维码
     */
    public function goodsQrcode() {
        $data = Db::table('huilife_goods')
            ->where(['qrcode' => NULL])
            ->limit(5)
            ->select();
        if (!empty($data)) {
            foreach ($data as $k=>$v) {
                $result = GoodsQrcode::GoodsCreateQrcode($v['id']);
                if ($result) {
                    $re = Db::table('huilife_goods')
                        ->where(['id' => $v['id']])
                        ->update(['qrcode' => $result]);
                    echo '商品'.$v['id'].'更新分享二维码成功。\r\n';
                }
            }
        }
    }

}